﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Leaf_SerialPort_Basis
{
    class Leaf_converion
    {
        /* Hex转化为string变量 */
        public string ToHexString(byte[] bytes, int tt)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int a = 0; a < tt; a++)
                {
                    strB.Append(bytes[a].ToString("X2"));
                    strB.Append(" ");
                }
                hexString = strB.ToString();
            }
            return hexString;
        }

        /* str转化为byte，"1234"->{0x12,0x34}*/
        public byte[] strToHexByte(string hexString)
        {
            //hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
            {
                hexString = hexString.Insert(hexString.Length - 1, 0.ToString());
            }
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return returnBytes;
        }
    }
}
